import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Check, Crown, Zap, Star } from 'lucide-react'
import { useState } from 'react'

interface PlanUpgradeDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  currentPlan: string
  userId: string
}

const PLAN_INFO = {
  basic: {
    name: '基础版',
    price: '¥29/月',
    icon: <Zap className="h-5 w-5" />,
    color: 'bg-blue-500',
    features: ['AI生成 100次/月', '语音合成 50次/月', '文案生成 30次/月', '1GB 存储空间']
  },
  pro: {
    name: '专业版',
    price: '¥99/月',
    icon: <Star className="h-5 w-5" />,
    color: 'bg-purple-500',
    features: ['AI生成 500次/月', '语音合成 200次/月', '文案生成 100次/月', '5GB 存储空间', '优先客服支持']
  },
  enterprise: {
    name: '企业版',
    price: '¥299/月',
    icon: <Crown className="h-5 w-5" />,
    color: 'bg-gold-500',
    features: ['无限制使用', '无限存储空间', '专属客服', 'API 接口', '定制化服务']
  }
}

export function PlanUpgradeDialog({ open, onOpenChange, currentPlan, userId }: PlanUpgradeDialogProps) {
  const [loading, setLoading] = useState<string | null>(null)
  
  const handleUpgrade = async (planType: string) => {
    setLoading(planType)
    try {
      const token = localStorage.getItem('token')
      if (!token) {
        alert('请先登录')
        return
      }
      
      const response = await fetch('/api/user/upgrade', {
        method: 'POST',
        headers: { 
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({ planType, durationMonths: 1 })
      })
      
      if (response.ok) {
        window.location.reload() // 刷新页面以更新用户信息
      } else {
        const errorData = await response.json()
        alert(`升级失败：${errorData.error || '请重试'}`)
      }
    } catch (error) {
      alert('升级失败，请重试')
    } finally {
      setLoading(null)
    }
  }
  
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl">
        <DialogHeader>
          <DialogTitle>选择您的套餐</DialogTitle>
        </DialogHeader>
        
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mt-4">
          {Object.entries(PLAN_INFO).map(([planKey, plan]) => {
            const isCurrentPlan = currentPlan === planKey
            const isDowngrade = ['basic', 'pro', 'enterprise'].indexOf(currentPlan) > ['basic', 'pro', 'enterprise'].indexOf(planKey)
            
            return (
              <Card key={planKey} className={`relative flex flex-col h-full ${isCurrentPlan ? 'ring-2 ring-blue-500' : ''}`}>
                {planKey === 'pro' && (
                  <Badge className="absolute -top-2 left-1/2 transform -translate-x-1/2 bg-purple-500">
                    推荐
                  </Badge>
                )}
                
                <CardHeader className="text-center">
                  <div className={`w-12 h-12 rounded-full ${plan.color} flex items-center justify-center mx-auto mb-2 text-white`}>
                    {plan.icon}
                  </div>
                  <CardTitle>{plan.name}</CardTitle>
                  <CardDescription className="text-2xl font-bold">{plan.price}</CardDescription>
                </CardHeader>
                
                <CardContent className="flex flex-col flex-1">
                  <ul className="space-y-2 mb-4 flex-1">
                    {plan.features.map((feature, index) => (
                      <li key={index} className="flex items-center">
                        <Check className="h-4 w-4 text-green-500 mr-2" />
                        <span className="text-sm">{feature}</span>
                      </li>
                    ))}
                  </ul>
                  
                  <Button 
                    className="w-full mt-auto" 
                    variant={isCurrentPlan ? 'secondary' : 'default'}
                    disabled={isCurrentPlan || isDowngrade || loading === planKey}
                    onClick={() => handleUpgrade(planKey)}
                  >
                    {loading === planKey ? '处理中...' : 
                     isCurrentPlan ? '当前套餐' : 
                     isDowngrade ? '不可降级' : '立即升级'}
                  </Button>
                </CardContent>
              </Card>
            )
          })}
        </div>
      </DialogContent>
    </Dialog>
  )
}